package com.turbo.cloud.ums.utils;

import com.turbo.cloud.ums.web.entity.UmsDept;
import com.turbo.cloud.ums.web.model.dept.UmsDeptVO;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DeptTreeUtil {
    /**
     * 获取所有权限
     *
     * @return
     */
    public static List<UmsDeptVO> getDeptTree(List<UmsDept> deptSourceList) {
        if (Objects.isNull(deptSourceList) || deptSourceList.isEmpty()) {
            return null;
        }
        // 定义新的list
        List<UmsDeptVO> deptTargetList = new ArrayList<>();
        // 先找到所有的一级分类
        for (UmsDept deptSource : deptSourceList) {
            // 一级菜单的parentId是0
            if ("0".equals(deptSource.getParentId())) {
                UmsDeptVO umsDeptVO = new UmsDeptVO();
                BeanUtils.copyProperties(deptSource, umsDeptVO);
                deptTargetList.add(umsDeptVO);
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (UmsDeptVO deptTarget : deptTargetList) {
            deptTarget.setChildren(getChildren(deptTarget.getId(), deptSourceList));
        }
        return deptTargetList;
    }

    /**
     * 递归查找子菜单
     *
     * @param id             当前菜单ID
     * @param deptSourceList 源菜单列表
     * @return
     */
    private static List<UmsDeptVO> getChildren(String id, List<UmsDept> deptSourceList) {
        //子级
        List<UmsDeptVO> deptChildrenList = new ArrayList<>();
        for (UmsDept deptSource : deptSourceList) {
            // 遍历所有节点，将父级id与传过来的id比较
            if (deptSource.getParentId().equals(id)) {
                UmsDeptVO umsDeptVO = new UmsDeptVO();
                BeanUtils.copyProperties(deptSource, umsDeptVO);
                deptChildrenList.add(umsDeptVO);
            }
        }
        // 把子级的子级再循环一遍
        for (UmsDeptVO deptTarget : deptChildrenList) {
            deptTarget.setChildren(getChildren(deptTarget.getId(), deptSourceList));
        }
        // 递归退出条件
        if (deptChildrenList.size() == 0) {
            return null;
        }
        return deptChildrenList;
    }

    /**
     * 根据岗位父级Id找到岗位子级Id
     *
     * @param parentId       父级ID
     * @param deptSourceList 源岗位列表
     */
    public static void getChildrenDeptIds(String parentId, List<UmsDept> sourceList, List<String> targetIds) {
        if (Objects.isNull(targetIds)) {
            targetIds = new ArrayList<>();
        }

        if(!targetIds.contains(parentId)) {
            targetIds.add(parentId);
        }

        for (UmsDept umsDept : sourceList) {
            if (parentId.equals(umsDept.getParentId())) {
                targetIds.add(umsDept.getId());
                getChildrenDeptIds(umsDept.getId(), sourceList, targetIds);
            }
        }
    }
}
